/**
 * Created by Freeman on 2016/8/8.
 */
import merge from 'lodash/merge'
import union from 'lodash/union'
import {
    ARTICLE_LIST_REQUEST,
    ARTICLE_LIST_SUCCESS,
    ARTICLE_LIST_FAILURE,
    ARTICLE_DETAIL_SUCCESS,
    ARTICLE_DETAIL_FAILURE,
    TOGGLE_LIKE_SUCCESS,
    TOGGLE_LIKE_FAILURE
} from '../constants/ActionTypes'

const initialState = {
    isFetching: false,
    isMore: true,
    items: []
}

export const articleList = (state = initialState, action) => {
    switch (action.type) {
        case ARTICLE_LIST_REQUEST:
            return merge({}, state, {isFetching: true});
        case ARTICLE_LIST_SUCCESS:
            let tmpItems = action.isAdd ? union(state.items, action.json.data) : action.json.data;
            return {
                ...state,
                isFetching: false,
                isMore: !(action.json.data.length < action.pageSize),
                items: tmpItems
            };
        case ARTICLE_LIST_FAILURE:
            return merge({}, state, {isFetching: false});
        default:
            return state;
    }
};

export const articleDetail = (state = {}, action) => {
    switch (action.type) {
        case ARTICLE_DETAIL_SUCCESS:
            return {
                ...state,
                ...action.articleDetail
            };
        case ARTICLE_DETAIL_FAILURE:
            return state;
        case TOGGLE_LIKE_SUCCESS:
            return {
                ...state,
                isLike:action.isLike,
                like_count:action.like_count
            };
        case TOGGLE_LIKE_FAILURE:
            return state;
        default:
            return state;
    }
};